﻿using System;
using NDBGen.Descriptors.Columns.DataTypes;

namespace NDBGen.Plugins.Descriptors.Columns.DataTypes
{
    [ColumnDataTypeScriptSnippetGenerator(typeof(StandardDataTypeDescriptor))]
    public sealed class SqlServerStandardDataTypeScriptGenerator : SqlServerScriptSnippetGeneratorBase<IColumnDataTypeDescriptor>, IColumnDataTypeScriptSnippetGenerator
    {
        private const String SQL_FORMAT = "[{0}] {1}";
        private const String SQL_LENGTH_FORMAT = "[{0}] {1}({2})";
        private const String SQL_SCALE_FORMAT = "[{0}] {1}({2},{3})";

        private String SqlDeclaration { get; set; }

        protected override void Init(IPluginData pluginData, IColumnDataTypeDescriptor descriptor)
        {
            base.Init(pluginData, descriptor);

            String sqlFormat;
            if (this.Descriptor.Column.Scale.HasValue)
            {
                sqlFormat = SQL_SCALE_FORMAT;
            }
            else if (this.Descriptor.Column.Length.HasValue || this.Descriptor.Column.DataType.IsMaxLengthType())
            {
                sqlFormat = SQL_LENGTH_FORMAT;
            }
            else
            {
                sqlFormat = SQL_FORMAT;
            }

            this.SqlDeclaration = String.Format(sqlFormat,
                this.Descriptor.Column.Name,
                this.Descriptor.Column.DataType.ToString().ToLower().Replace("max", String.Empty),
                (Object)this.Descriptor.Column.Length ?? (this.Descriptor.Column.DataType.IsMaxLengthType() ? "max" : String.Empty),
                (Object)this.Descriptor.Column.Scale ?? String.Empty);
        }

        void IColumnDataTypeScriptSnippetGenerator.WriteSql(IIndentedTextWriter writer)
        {
            writer.Write(this.SqlDeclaration);
        }
    }
}